package com.example.attempt.controller;

import com.example.attempt.entity.Homework;
import com.example.attempt.entity.HomeworkWithFile;
import com.example.attempt.service.impl.CourseServiceImpl;
import com.example.attempt.service.impl.HomeworkServiceImpl;
import com.example.attempt.service.impl.SubmitServiceImpl;
import com.example.attempt.service.impl.TeacherServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@RestController
public class HomeworkController {
    @Autowired
    private HomeworkServiceImpl homeworkService;
    @Autowired
    private TeacherServiceImpl teacherService;
    @Autowired
    private CourseServiceImpl courseService;
    @Autowired
    private SubmitServiceImpl submitService;
    private final String mypath="D:\\IDEA\\mutual-evaluation\\src\\main\\resources\\homework\\";
    @PostMapping(path = "/getHomeworkByHid")
    public Homework getHomeworkByHid(@RequestParam(value = "hid") int hid){
        System.out.println("得到作业");
        Homework h=homeworkService.queryByHid(hid);
        System.out.println(h.toString());
        return h;
    }

    @PostMapping(path = "/getHomeworkByCid")
    public List<Homework> getHomeworkByCid(@RequestParam(value = "cid") String cid){
        List<Homework> homeworkList=homeworkService.queryByCid(cid);
        for (Homework homework : homeworkList) {
            homework.setSubmitNumber(submitService.getSubmitNumber(homework.getHid()));
        }
        System.out.println(homeworkList);
        return homeworkList;
    }

    //互评截止时间
    @PostMapping(path = "/getDtime")
    public LocalDateTime getDtime(@RequestParam(value = "hid") int hid){
        if(homeworkService.queryByHid(hid)==null)
            return null;
        return homeworkService.queryByHid(hid).getDtime();
    }

    //是否已经查重
    @PostMapping(path = "/getIsCheck")
    public int getIsCheck(@RequestParam(value = "hid") int hid){
        if(homeworkService.queryByHid(hid)==null)
            return -1;
        return homeworkService.queryByHid(hid).getIsCheck();
    }
    @PostMapping(path = "/changeHomework1")
    public int changeHomework1(@RequestParam(value = "hid") int hid,
                              @RequestParam(value = "content") String content,
                              @RequestParam(value = "ddl") String ddl
                              ){
        String link;
        Homework homework=homeworkService.queryByHid(hid);

        homework.setContent(content);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime htime = LocalDateTime.parse(ddl,df);
        homework.setHTime(htime);
        System.out.println("修改作业"+homework);
        homeworkService.updateHomework(homework);
        return 1;
    }
    //编辑作业
    @PostMapping(path = "/changeHomework")
    public int changeHomework(@RequestParam(value = "hid") int hid,
                              @RequestParam(value = "content") String content,
                              @RequestParam(value = "ddl") String ddl,
                              @RequestParam(value = "file") MultipartFile file){
        String link;
        Homework homework=homeworkService.queryByHid(hid);

        homework.setContent(content);
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime htime = LocalDateTime.parse(ddl,df);
        homework.setHTime(htime);
        if (file!=null){
            try {
                String filePath1 = mypath+hid;
                //生成文件夹
                File file1=new File(filePath1);
                if(!file1.exists()){	//如果_test2文件夹不存在
                    file1.mkdir();
                }
                else{
                    File[] files = file1.listFiles();
                    //遍历该目录下的文件对象
                    for (File f: files){
                        //打印文件名
                        String name = file1.getName();
                        System.out.println(name);
                        f.delete();
                    }
                }
                InputStream inputStream = file.getInputStream();
                String filePath = filePath1 +"\\"+ file.getOriginalFilename();
                OutputStream outputStream = new FileOutputStream(filePath);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer,0,len);
                }
                InetAddress localHost = InetAddress.getLocalHost();
//                link=localHost.getHostAddress();
                link="http://lyycf.natapp1.cc/homework/"+hid+"/"+file.getOriginalFilename();
                homework.setHlink(link);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        homeworkService.updateHomework(homework);
        return 1;
    }
    @PostMapping(path = "/setRate")
    public int setRate(@RequestParam(value = "student") float stuRate,
                       @RequestParam(value = "assistance") float assistRate,
                       @RequestParam(value = "teacher") float teacherRate,
                       @RequestParam(value = "hid") int hid){
        System.out.println("jjj");
       if(homeworkService.queryByHid(hid)==null){
           return -2;
       }
       else if(stuRate<0||assistRate<0||teacherRate<0){
           return -1;
       }
       else if(stuRate+assistRate+teacherRate!=1){
           return 0;
       }
       else {
           homeworkService.updateRate(hid, stuRate, assistRate, teacherRate);
           return 1;
       }
    }
    @PostMapping(path = "/addHomework1")
    public int addHomework1(@RequestParam(value = "cid") String cid,
                            @RequestParam(value = "content") String content,
                            @RequestParam(value = "time") String time,
                            @RequestParam(value = "tid") String tid,
                            @RequestParam(value = "studentRate") float studentRate,
                            @RequestParam(value = "assistanceRate") float assistanceRate,
                            @RequestParam(value = "teacherRate") float teacherRate,
                            @RequestParam(value = "threshold") double threshold,
                            @RequestParam(value ="title") String title
                            ){
        if (courseService.queryById(cid)==null)
            return -4;
        if (teacherService.queryById(tid)==null)
            return -3;
        if (studentRate<0 || assistanceRate<0 || teacherRate<0)
            return -2;
//        if (homework.getStudentRate() + homework.getAssistanceRate() + homework.getTeacherRate() != 1)
//            return -1;
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime htime = LocalDateTime.parse(time,df);
        if (!htime.isAfter(LocalDateTime.now()))
            return 0;
        String link="";
        Homework h=new Homework(1, tid, cid, htime, title,
                content, link, studentRate,teacherRate,
        assistanceRate, threshold, 0,
        null, 0,0);
        homeworkService.addHomework(h);
        return 1;
    }

    @PostMapping(path = "/addHomework")
    @ResponseBody
    public int addHomework(HomeworkWithFile homework){
        homework.getTime();
        System.out.println(homework);
        String link="";
        MultipartFile multifile= homework.getHFile();
        if (courseService.queryById(homework.getCid())==null)
            return -4;
        if (teacherService.queryById(homework.getTid())==null)
            return -3;
        if (homework.getStudentRate()<0 || homework.getAssistanceRate()<0 || homework.getTeacherRate()<0)
            return -2;
//        if (homework.getStudentRate() + homework.getAssistanceRate() + homework.getTeacherRate() != 1)
//            return -1;
        if (!homework.getHtime().isAfter(LocalDateTime.now()))
            return 0;

        if (multifile==null){
            link="";
            Homework h=new Homework(homework," ");
            homeworkService.addHomework(h);
        }
        else{
            try {
                Homework h=new Homework(homework," ");
                homeworkService.addHomework(h);
                System.out.println("添加成功");
                System.out.println("进行中");
                String filePath1 = mypath+homeworkService.getNowHid();
                //生成文件夹
                File file1=new File(filePath1);
                if(!file1.exists()){	//如果_test2文件夹不存在
                    file1.mkdir();		//创建文件夹
                }
                System.out.println("aaaa");
                InputStream inputStream = multifile.getInputStream();
                String filePath = filePath1 +"\\"+ multifile.getOriginalFilename();
                OutputStream outputStream = new FileOutputStream(filePath);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) > 0) {
                    outputStream.write(buffer,0,len);
                }
                InetAddress localHost = InetAddress.getLocalHost();
                link=localHost.getHostAddress();
                System.out.println("ccc");
                link="http://lyycf.natapp1.cc/homework/"+homeworkService.getNowHid()+"/"+multifile.getOriginalFilename();
                System.out.println(homeworkService.getNowHid());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        homeworkService.setLink(link,homeworkService.getNowHid());
        System.out.println("添加成功");
        return 1;
    }

    @PostMapping(path = "/setThreshold")
    public int setThreshold(@RequestParam(value = "hid") int hid,
                            @RequestParam(value = "threshold") double threshold){
//        if(homeworkService.queryByHid(hid)==null)
//            return -1;
        homeworkService.setThreshold(hid,threshold);
        return 0;
    }

}
